package com.arnold.demo.journal.common;

/**
 * Created by fab.yin on 11/23/2016.
 */

import com.arnold.demo.journal.config.Config;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisUtil {
    private static JedisPool pool = null;

    public static JedisPool getPool() {
        if (pool == null) {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(Config.REDIS_MAXTOTAL());
            config.setMaxIdle(Config.REDIS_MAXIDLE());
            config.setMaxWaitMillis(Config.REDIS_MAXWAITMILLIS());
            config.setTestOnBorrow(true);
            pool = new JedisPool(config, Config.REDIS_HOST(), Config.REDIS_PORT());
        }
        return pool;
    }

    public static void returnResource(JedisPool pool, Jedis redis) {
        if (redis != null) {
            pool.returnResource(redis);
        }
    }

    public static Jedis getJedis() {
        Jedis jedis = null;
        int count = 0;
        do {
            try {
                jedis = getPool().getResource();
            } catch (Exception e) {
                getPool().returnBrokenResource(jedis);
            }
            count++;
        } while (jedis == null && count < 3);
        return jedis;
    }

}
